package com.anpy.user.service.impl;

import com.anpy.user.entity.RoleEntity;
import com.anpy.user.mapper.RoleMapper;
import com.anpy.user.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 角色服务实现类
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RoleEntity> implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createRole(RoleEntity roleEntity) {
        // 设置创建时间
        roleEntity.setCreatedAt(new Date());
        
        // 保存角色基本信息
        boolean result = save(roleEntity);
        
        // 如果有权限信息，保存权限关联
        if (result && roleEntity.getPermissions() != null && !roleEntity.getPermissions().isEmpty()) {
            roleMapper.saveRolePermissions(roleEntity.getId(), roleEntity.getPermissions());
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRole(RoleEntity roleEntity) {
        // 更新角色基本信息
        boolean result = updateById(roleEntity);
        
        // 如果有权限信息，更新权限关联
        if (result && roleEntity.getPermissions() != null) {
            // 先删除原有权限
            roleMapper.deleteRolePermissions(roleEntity.getId());
            
            // 再添加新权限（如果有的话）
            if (!roleEntity.getPermissions().isEmpty()) {
                roleMapper.saveRolePermissions(roleEntity.getId(), roleEntity.getPermissions());
            }
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRole(Integer roleId) {
        // 先删除角色权限关联
        roleMapper.deleteRolePermissions(roleId);
        
        // 再删除角色
        return removeById(roleId);
    }

    @Override
    public RoleEntity getRoleById(Integer roleId) {
        // 获取角色基本信息
        RoleEntity roleEntity = getById(roleId);
        
        if (roleEntity != null) {
            // 获取角色权限信息
            List<String> permissions = roleMapper.getRolePermissions(roleId);
            roleEntity.setPermissions(permissions);
        }
        
        return roleEntity;
    }

    @Override
    public List<RoleEntity> getAllRoles() {
        List<RoleEntity> roles = list();
        
        // 为每个角色加载权限信息
        for (RoleEntity role : roles) {
            List<String> permissions = roleMapper.getRolePermissions(role.getId());
            role.setPermissions(permissions);
        }
        
        return roles;
    }

    @Override
    public Page<RoleEntity> getRolesByPage(int page, int size, String name, Boolean status) {
        // 构建查询条件
        LambdaQueryWrapper<RoleEntity> queryWrapper = new LambdaQueryWrapper<>();
        
        // 如果有名称参数，添加模糊查询条件
        if (StringUtils.hasText(name)) {
            queryWrapper.like(RoleEntity::getName, name);
        }
        
        // 如果有状态参数，添加精确查询条件
        if (status != null) {
            queryWrapper.eq(RoleEntity::getStatus, status);
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(RoleEntity::getCreatedAt);
        
        // 执行分页查询
        Page<RoleEntity> rolePage = page(new Page<>(page, size), queryWrapper);
        
        // 为每个角色加载权限信息
        for (RoleEntity role : rolePage.getRecords()) {
            List<String> permissions = roleMapper.getRolePermissions(role.getId());
            role.setPermissions(permissions);
        }
        
        return rolePage;
    }

    @Override
    public boolean updateRoleStatus(Integer roleId, Boolean status) {
        RoleEntity role = new RoleEntity();
        role.setId(roleId);
        role.setStatus(status);
        return updateById(role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean assignPermissions(Integer roleId, List<String> permissions) {
        // 先删除原有权限
        roleMapper.deleteRolePermissions(roleId);
        
        // 再添加新权限（如果有的话）
        if (permissions != null && !permissions.isEmpty()) {
            return roleMapper.saveRolePermissions(roleId, permissions) > 0;
        }
        
        return true;
    }

    @Override
    public List<String> getRolePermissions(Integer roleId) {
        return roleMapper.getRolePermissions(roleId);
    }
}
